package misc

import (
	"errors"
	"fmt"
	"github.com/nsf/termbox-go"
	"slices"
	"sync"
)

type KeyBoard struct {
	initialized bool
	Mutex       sync.Mutex
}

var _keyboard = &KeyBoard{
	initialized: false,
}

func init() {
	sync.NewCond(&_keyboard.Mutex)
}

func Initialize() error {
	defer _keyboard.Mutex.Unlock()
	_keyboard.Mutex.Lock()
	if _keyboard.initialized {
		return nil
	}
	err := termbox.Init()
	if err == nil {
		_keyboard.initialized = true
		return nil
	}

	return err
}

func Destroy() {
	defer _keyboard.Mutex.Unlock()
	_keyboard.Mutex.Lock()
	if _keyboard.initialized {
		termbox.Close()
		_keyboard.initialized = false
		return
	}
}

func WaitKeyDown(prompt string, Keys []uint16) (uint16, error) {

	_keyboard.Mutex.Lock()
	if !_keyboard.initialized {
		_keyboard.Mutex.Unlock()
		return 0, errors.New("keyboard hasn't been initialized")
	}
	_keyboard.Mutex.Unlock()

	fmt.Println(prompt)
	for {

		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			if slices.Index(Keys, uint16(ev.Ch)) != -1 {
				return uint16(ev.Key), nil
			}
		default:
			continue
		}

	}
}

func WaitAnyKeyDown(prompt string) (uint16, error) {
	_keyboard.Mutex.Lock()
	if !_keyboard.initialized {
		_keyboard.Mutex.Unlock()
		return 0, errors.New("keyboard hasn't been initialized")
	}
	_keyboard.Mutex.Unlock()

	fmt.Println(prompt)

	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			return uint16(ev.Key), nil
		default:
			continue
		}

	}
}
